
package com.jz.community.basecomm.net.retrofit;

import android.content.Context;

import com.jz.community.basecomm.bean.baseCommInfo.BaseEmbedded;
import com.jz.community.commview.view.widget.ProgressDialogManager;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by Tony.Fan on 2016/8/10.
 * 对retrofit Rx 加载进度条进行包装
 * 用法
 */

public class RxLoadingWrapper<T> {

    private Context ctx;
    private boolean needDialog = false;


    /**
     * 默认有进度条
     *
     * @param ctx
     */

    public RxLoadingWrapper(Context ctx) {
        this(ctx, true);
    }


    /**
     * 可以设置 是否需要进度条
     *
     * @param ctx
     * @param needDialog
     */

    public RxLoadingWrapper(Context ctx, boolean needDialog) {
        this.ctx = ctx;
        this.needDialog = needDialog;
    }


    /**
     * 执行，回调具体的数据 泛型Embedded解析
     *
     * @param observable observable
     * @return
     */

    public Observable<BaseEmbedded<T>> gExecute(Observable<BaseEmbedded<T>> observable) {
        return observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable t) throws Exception {
                        if (needDialog) {
                            ProgressDialogManager.showDialog(ctx);
                        }
                    }
                })
                .doOnComplete(() -> ProgressDialogManager.dismissProgressDialog())
                .doOnError(e -> ProgressDialogManager.dismissProgressDialog());
    }


    /**
     * 执行，回调具体的数据 普通解析
     *
     * @param observable observable
     * @return
     */

    public Observable<T> execute(Observable<T> observable) {
        return observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable t) throws Exception {
                        if (needDialog) {
                            ProgressDialogManager.showDialog(ctx);
                        }
                    }
                })
                .doOnComplete(() -> ProgressDialogManager.dismissProgressDialog())
                .doOnError(e -> ProgressDialogManager.dismissProgressDialog());
    }

}

